<template>
    <div class="img-list-page">
        <div class="gp-filter">
            <div class="gp-img-layout">
                <!-- <DropDown :list="tagFilter" :value.sync="queryParams.rank" :tlist="tList"
                    :subvalue.sync="queryParams.orderByColumn" @change="handleSearch()" style="min-width: 150px;"
                    placeholder="" /> -->
                <DropDown :list="tList" :value.sync="queryParams.orderByColumn" :tlist="tagFilter"
                :subvalue.sync="queryParams.rank" @change="handleSearch()" style="min-width: 150px;" placeholder="" />    
                <div class="label-filter">
                    <span class="tit">平台</span>
                    <div class="plat-items">
                        <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
                            <i class="sm-tip" slot-content>PC</i>
                            <span slot="reference" class="pitem windows"
                                :class="{ 'active': queryParams.device == 'PC' }" @click="chooseDevice('PC')"></span>
                        </el-popover>
                        <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
                            <i class="sm-tip" slot-content>主机</i>
                            <span slot="reference" class="pitem xbox" :class="{ 'active': queryParams.device == '主机' }"
                                @click="chooseDevice('主机')"></span></el-popover>
                        <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
                            <i class="sm-tip" slot-content>掌机</i>
                            <span slot="reference" class="pitem switch"
                                :class="{ 'active': queryParams.device == '掌机' }"
                                @click="chooseDevice('掌机')"></span></el-popover>
                        <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
                            <i class="sm-tip" slot-content>手游</i>
                            <span slot="reference" class="pitem apple" :class="{ 'active': queryParams.device == '手游' }"
                                @click="chooseDevice('手游')"></span></el-popover>
                    </div>
                </div>
                <div class="label-filter">
                    <span class="tit">版式</span>
                    <div class="plat-items">
                        <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
                            <i class="sm-tip" slot-content>横屏</i>
                            <span slot="reference" class="pitem h-screen"
                                :class="{ 'active': queryParams.orientation == '横屏' }"
                                @click="chooseScreen('横屏')"></span></el-popover>
                        <el-popover popper-class="gm-info-pop" placement="top-start" trigger="hover">
                            <i class="sm-tip" slot-content>竖屏</i>
                            <span slot="reference" class="pitem s-screen"
                                :class="{ 'active': queryParams.orientation == '竖屏' }"
                                @click="chooseScreen('竖屏')"></span></el-popover>
                    </div>
                </div>
                <div class="label-filter column-filter">
                    <span class="tit">列数</span>
                    <div class="lbs-slider">
                        <el-slider class="lbs-slider-control" :min="2" :max="6" :show-tooltip="true"
                            v-model="columns"></el-slider>
                    </div>
                </div>
                <div class="seach-bx" :class="{ 'active': searchIsFocus }">
                    <div class="q-f-item-wrap">
                        <template v-for="c in cateObj">
                            <div class="q-f-item" v-for="s in c.items" v-if="s.selected"><span class="ct">{{ c.name
                                    }}</span><span class="ct-val">{{ s.title }}</span><i class="it-clr"
                                    @click="onParamterClear(c, s)"></i>
                            </div>
                        </template>
                        <input type="text" @focus="searchIsFocus = true" @blur="searchIsFocus = false"
                            v-model="queryParams.title" @keypress.enter="handleSearch"
                            :placeholder="'搜索 ' + inspirationInfo.imageNum + ' 张图片中的文字…'" /><a
                            class="cancel-search" v-if="queryParams.title" @click="queryParams.title=''"></a>
                    </div>
                </div>
                <div class="bs-g-flabel gpic-clr" :class="{'is-fenw':showFnew&&queryParams.imageColor}">
                    <div class="cur">
                        <input type="text" id="colorfilter" style="display: none;">
                        <span v-if="queryParams.imageColor" :style="{ backgroundColor: queryParams.imageColor }"
                            class="query-color"></span>颜色 <i v-if="queryParams.imageColor"
                            @click="handleClear('imageColor')" class="clear-by-search"></i>
                    </div>
                    <div class="games-filter" v-if="queryParams.imageColor">
                        <div class="games-filter-wrap color-wrap">
                            <div class="rtzd">
                                准确度：
                                <div class="rtzd-box">
                                    <el-slider :min="0" tooltip-class="no-tip" v-model="queryParams.colorrto"
                                        @change="onColorRtoChange" :max="80"></el-slider><span class="rto-val">{{
                                        queryParams.colorrto}}</span>
                                </div>
                            </div>
                            <!-- <div class="gft-data-box">
                                    <ul class="data-ul colors">
                                        <li v-for="(color,idx) in defaultColors" :key="idx" @click="chooseByColor(color)" :class="{'active':color==queryParams.imageColor}"><a :style="{backgroundColor:color}"></a></li>
                                    </ul>
                                </div> -->
                        </div>
                    </div>
                    <div class="game-n-u-visit img-color-fenw" v-if="showFnew&&queryParams.imageColor">
                        <div class="nv-content">
                            <div class="nv-content-l">
                                <span>「悬浮这里，显示调节滑块」</span>
                                <span>数值越低越贴近主色调</span>
                            </div>
                            <a class="n-u-v-close" @click="handlCloseTop"></a>
                        </div>
                    </div>
                </div>
                <a class="bs-g-flabel" @click="showFilter = !showFilter">
                    <span class="cur">筛选</span>
                </a>
            </div>
            <!-- <div class="seach-bx mobile" :class="{ 'active': searchIsFocus }">
                <div class="q-f-item-wrap">
                    <template v-for="c in cateObj">
                        <div class="q-f-item" v-for="s in c.items" v-if="s.selected"><span class="ct">{{ c.name
                                }}</span><span class="ct-val">{{ s.title }}</span><i class="it-clr"
                                @click="onParamterClear(c, s)"></i>
                        </div>
                    </template>
                    <input type="text" @focus="searchIsFocus = true" @blur="searchIsFocus = false"
                        v-model="queryParams.title" @keypress.enter="handleSearch"
                        :placeholder="'按标题/风格/类型等搜索 ' + inspirationInfo.imageNum + ' 张截图'" /><a class="cancel-search"
                        v-if="queryParams.title" @click="handleXClear"></a>
                </div>
            </div> -->
        </div>
        <div class="img-datas">
            <div class="img-list" v-if="!isDataError">
                <WaterfallFlowImgList ref="refWaf" id="1" :list="list" :columns="columns" />
                <div class="no-more-text" v-if="!hasMore && !isloading && list.length > 0">没有更多了</div>
                <Empty text="没有找到符合条件的结果~" v-if="!isloading && list.length == 0" />
            </div>
            <div class="web-data-error" v-if="isDataError">
                <div class="tip-text">别走开刷新一下，有所爱才有所期待～</div>
                <div class="options">
                    <a class="go-back" href="/">返回首页</a>
                    <a class="click-refresh" @click="isDataError = false; handleSearch();">点击刷新</a>
                </div>
            </div>
            <FilterBy class="sch-sticky" :cates="cateObj" ref="refFilterBy" :params="queryParams" @change="onFilterChange" viewnumfield="imageNum"
                v-show="showFilter && cateObj.length > 0" />
        </div>

        <div class="pro-bot-loading" v-if="isloading">
            <i class="el-icon-loading"></i>
        </div>

        <div class="loading-mask" v-if="isloading"></div>
    </div>
</template>

<script>
import { mapState} from 'vuex'
import Empty from '@/components/Empty'
import FilterBy from '@/components/FilterBy'
import DropDown from '@/components/dropdown'
import api from '@/api/api'
import "../../../static/utils/jquery.js";
require('../../../static/utils/spectrum.js');
export default {
    name: 'homes',
    props: ['filterparams', 'filtercates'],
    data() {
        return {
            showFnew:false,
            searchIsFocus: false,
            isDataError: false,
            isloading: true,
            tList: [],
            cateObj: [],
            showFilter: true,
            tagFilter: [],
            gTypes: [],
            isFocus: false,
            model: 'small',
            isCkAll: false,
            curViewidx: 0,
            collectIds: [],
            gap: 273,
            showFav: false,
            defaultColors: ['#BFDA6D', '#F3DE64', '#F8A650', '#E96248', '#4D4D4D', '#9DC6C8', '#6998D0', '#7368EE', '#965C23', '#DAA36D', '#FFFFFF', '#C36DDA'],
            curImgId: '',
            currentImgUrl: '',
            showInfo: false,
            scrollLoaded: false,
            hasMore: true,
            queryParams: {
                colorrto: 10,
                imageColor: '',
                pageNum: 1,
                pageSize: 50,
                isAsc: 'DESC',
                orderByColumn: 'createTime',
                rank: '',
                color: '',
                categoryId: 22,
                last: ''
            },
            slickSettings: {
                slidesToShow: 7,
                slidesToScroll: 1,
                infinite: false
            },
            inspirationInfo: {
                imageNum: 0,
                content: '',
                articleNum: 0
            },
            list: [],
            curFullPath: '',
            columns: 7
        }
    },
    components: {
        WaterfallFlowImgList: () => import('../../components/WaterfallFlowImgList'),
        DropDown, FilterBy, Empty
    },
    computed: {
        ...mapState(['ishiddenbar']),
        swiper() {
            return this.$refs.mySwiper.swiper
        },
        selectIds() {
            let datas = this.list.filter(r => {
                return r.selected
            });
            let ids = datas.map(item => {
                return item.thumbnailBean.id;
            })
            this.isCkAll = ids.length == this.list.length;
            return ids;
        }
    },
    watch: {
        showFilter() {
            let that=this;
            setTimeout(()=>{
                that.$refs['refWaf'].initLineGap();
            },150)
        },
        ishiddenbar(){
            let that=this;
            setTimeout(()=>{
                that.$refs['refWaf'].initLineGap();
            },150)
        }
        // ,
        // columns() {
        //     let gap = document.getElementsByClassName('vue-waterfall')[0].offsetWidth / this.columns;
        //     gap = gap < 268 ? document.getElementsByClassName('vue-waterfall')[0].offsetWidth / 4 : gap;
        //     this.gap = gap;
        // }
    },
    methods: {
        handlCloseTop(){
           if(this.showFnew){
            this.showFnew=false;
            localStorage.setItem('IMG-COLOR-NYD',false);
           }
        },
        onColorRtoChange() {
            this.handlCloseTop();
            this.handleSearch();
        },
        handleXClear() {
            this.cateObj.map(item => {
                item.items.map(sub => {
                    sub.selected = false;
                })
            })
            this.queryParams = {
                pageNum: 1,
                pageSize: 50,
                orderByColumn: 'createTime',
                isAsc: 'DESC',
                rank: '首页推荐',
                color: '',
                categoryId: 22
            }
            this.handleSearch();
        },
        onParamterClear(parent, sub) {
            this.$refs['refFilterBy'].handleSelSub(parent, sub);
        },
        onFilterChange(_params, _type, _allCate) {
            this.cateObj = _allCate;
            // if (_type == '22') {
            //     this.$emit('changepage', _params, _type, _allCate);
            // } else {
                this.queryParams = Object.assign(this.queryParams, _params);
                this.handleSearch();
            // }
        },
        handleCancelByGtypeAll() {
            this.gTypes.map(item => {
                item.selected = false;
            })
            this.queryParams.categoryIds = '';
            this.handleSearch();
        },
        handleConfirmByGTypeSearch() {
            let _categoryIds = [];
            this.gTypes.map(item => {
                if (item.selected) {
                    _categoryIds.push(item.value);
                }
            })
            this.queryParams.categoryIds = _categoryIds.join(',');
            this.handleSearch();
        },
        handleClear(_property) {
            this.queryParams[_property] = '';
            this.handleSearch();
        },
        chooseByColor(_clr) {
            this.queryParams.imageColor = _clr;
            this.handleSearch();
        },
        handleSelectAll() {
            let that = this;
            if (that.selectIds.length != that.list.length) {
                this.list.map(item => {
                    item.selected = true;
                })
            }
            else {
                this.list.map(item => {
                    item.selected = !that.isCkAll;
                })
            }
        },
        onFavSucc() {
            this.list.map(item => {
                item.selected = false;
            })
            this.showFav = false;
        },
        onImgError(e) {
            e.target.src = require('../../assets/pro/default_uimg.svg');
        },
        async handleCancelFav(_imgId) {
            let res = await api.cancelFavToSingleCollect({ id: _imgId })
        },
        handleSelectImgItem(item) {
            item.selected = !item.selected;
        },
        chooseDevice(_device) {
            let that=this;

            let pd=this.cateObj.filter(r=>{
                return r.queryfield=='device';
            })
            let p=pd[0].items.filter(r=>{return r.value==_device});

            this.$refs['refFilterBy'].handleSelSub(pd[0],p[0]);

            // this.cateObj.map(item => {
            //     if (item.queryfield == 'device') {
            //     item.items.map(r => {
            //         r.selected = false;
            //         if (r.value == _device&&that.queryParams.device!=r.value) r.selected = true;
            //     })
            //     }
            // })
            // this.$refs['refFilterBy'].cateObj=this.cateObj;
            // this.$forceUpdate();
            // this.queryParams.device = _device == this.queryParams.device ? '' : _device;
            
            // this.handleSearch();
        },
        chooseScreen(_screen) {
            let pd=this.cateObj.filter(r=>{
                return r.queryfield=='orientation';
            })
            let p=pd[0].items.filter(r=>{return r.value==_screen});

            this.$refs['refFilterBy'].handleSelSub(pd[0],p[0]);

            // let that=this;
            // this.cateObj.map(item => {
            //     if (item.queryfield == 'orientation') {
            //     item.items.map(r => {
            //         r.selected = false;
            //         if (r.value == _screen&&that.queryParams.orientation!=r.value) r.selected = true;
            //     })
            //     }
            // })
            // this.queryParams.orientation = _screen == this.queryParams.orientation ? '' : _screen;

            // this.handleSearch();
            
        },
        handleSearch(e) {
            if (e) e.target.blur();
            
            window.history.pushState({}, 0,e&&e.target.value?('?t=10&k='+e.target.value):'?t=10');
            this.queryParams.last = '';
            this.isDataError = false;
            this.queryParams.pageNum = 1;
            this.list = [];
            this.scrollLoaded = false;
            this.hasMore = true;
            this.queryList();
        },
        onInfoClose() {
            window.history.pushState({}, 0, this.curFullPath);
            document.body.style.overflow = 'inherit';
            this.showInfo = false;
        },
        handleShowInfo(_item, _idx) {
            if (this.selectIds.length > 0) {
                _item.selected = !_item.selected;
                return;
            }
            this.curViewidx = _idx;
            this.curImgId = _item.thumbnailBean.id;
            this.currentImgUrl = _item.thumbnail;
            window.history.pushState({}, 0, '/imgv/' + _item.id + '?imgurl=' + this.currentImgUrl);
            document.body.style.overflow = 'hidden';
            this.showInfo = true;
        },
        handleLoadingMore() {
            this.queryParams.pageNum++;
            this.queryList();
        },
        calculateTilt(corners){
            const{x:x1,y:y1}=corners[0];//左上
            const{x:x2,y:y2}=corners[1];// 右上
            // 计算 dy 和 dx
            const dy=y2-y1;
            const dx=x2-x1;
            //计算倾角(弧度->角度)
            const angle =Math.atan2(dy,dx)*(180 /Math.PI);
            // 返回角度
            return angle;
        },
        async queryList() {
            var that = this;

            this.isloading = true;
            // const loading = this.$loading({
            //     lock: true,
            //     text: '努力加载中...',
            //     spinner: 'el-icon-loading',
            //     background: 'rgba(0, 0, 0, 0.7)'
            // });
            if(that.queryParams.pageNum==1){
                // this.list=this.$bhelper.vlist;
            }
            
            api.searchImgs(that.queryParams).then(result => {
                
                let old = that.list;

                // let datas=result.data;
                let datas = result.data.images.list;
                datas.forEach(item => {
                    item.show=false;item.showOther=false;
                    that.$bhelper.convertImgItem(item,that);
                })
                
                if (that.queryParams.pageNum == 1) {
                    that.list =datas;
                }
                else{
                    that.list = [...old, ...datas];
                }

                that.total = result.total;

                if (datas.length > 0)
                    that.queryParams.last = datas[datas.length - 1].id;

                if ((result.data && (result.data.length < that.queryParams.pageSize || result.data.length == 0)) || datas.length < that.queryParams.pageSize) {
                    that.hasMore = false;
                } else {
                    that.hasMore = true;
                }

                setTimeout(()=>{
                    that.isloading = false;
                },300)
                setTimeout(()=>{
                    that.scrollLoaded = true;
                },1000)
            }).catch(res => {
                that.list=[];
                that.isloading=false;
                that.isDataError = true;
                // loading.close();
            })
        },
        handlePrev() {
            this.swiper.slidePrev()
        },
        handleNext() {
            this.swiper.slideNext()
        },
        docScroll() {
            let that = this;
            let jHeight = document.documentElement.scrollHeight - document.documentElement.scrollTop - document.documentElement.clientHeight;

            if (that.scrollLoaded == false) return;

            if (jHeight <= 1000 && that.hasMore) {
                if (!localStorage.getItem('token')) {
                    that.$parent.$parent.noLoginIsTak = false;
                    that.$parent.$parent.showLoginView = true;
                    that.isloading = false;
                    window.removeEventListener('scroll', that.docScroll);
                    return;
                }
                that.scrollLoaded = false;
                that.handleLoadingMore();
            }
        }
    },
    destroyed() {
        window.removeEventListener('scroll', this.docScroll)
        // $(window).unbind('resize');
    },
    async mounted() {
        if(!localStorage.getItem('IMG-COLOR-NYD')){
            this.showFnew=true;
        }
        $('body,html').animate({ scrollTop: 0 }, 300);
        if (this.filterparams) {
            this.queryParams = Object.assign(this.queryParams, this.filterparams);
        }

        // this.queryParams.praise=localStorage.getItem('userId');
        let res = await api.getCategoryFilter({ type: 'linggan', subType: 'image' });
        res.data.tags.map(item=>{
            if(item.title=='全部推荐'){
                item.title='全部截图';
            }
        })
        this.tagFilter = res.data.tags.filter(r => {
            return r.title != '编辑精选' && r.title != '普通推荐'
        });
        this.tList = res.data.news;

        let _gTypes = localStorage.getItem('G-TYPES')
        _gTypes = JSON.parse(decodeURIComponent(_gTypes))
        _gTypes.map(item => {
            item.selected = false;
        })
        this.gTypes = _gTypes


        let that = this;

        // if(document.getElementsByClassName('vue-waterfall').length>0)
        // {
        //     let gap=document.getElementsByClassName('vue-waterfall')[0].offsetWidth/this.columns;
        //     gap=gap<268?document.getElementsByClassName('vue-waterfall')[0].offsetWidth/4:gap;
        //     this.gap=gap;
        // }
        // $(window).resize(function(){
        //     if(document.getElementsByClassName('vue-waterfall').length>0){
        //         let gap=document.getElementsByClassName('vue-waterfall')[0].offsetWidth/that.columns;
        //         gap=gap<268?document.getElementsByClassName('vue-waterfall')[0].offsetWidth/4:gap;
        //         that.gap=gap;
        //     }
        // })

        this.curFullPath = this.$route.fullPath;

        let _k=this.$route.query.k;
        if(_k){
            this.queryParams.title=_k;
        }
        this.queryList();

        // let res=await api.getUserCollectsByUserId(localStorage.getItem('userId'));
        // if(res.code==0){
        //     this.collectIds=res.data;
        //     localStorage.setItem('US-COLLECTS',encodeURIComponent(JSON.stringify(res.data)))
        // }

        let _allCateTypes = JSON.parse(decodeURIComponent(localStorage.getItem('OBJ-CATE-ALL-TYPES')));
        let _cdatas = [];
        _cdatas.push({ name: '风格', items: _allCateTypes.styles, queryfield: 'style' })
        _cdatas.push({ name: '类型', items: _allCateTypes.categorys, queryfield: 'categoryIds' })
        _cdatas.push({ name: '主题', items: _allCateTypes.themes, queryfield: 'tags' })
        _cdatas.push({ name: '功能', items: _allCateTypes.funs, queryfield: 'paramImagesDescFunc' })
        _cdatas.push({ name: '材质图案', items: _allCateTypes.materials, queryfield: 'paramImagesDescMaterial' })
        _cdatas.push({ name: '平台', items: _allCateTypes.devices, queryfield: 'device' })
        _cdatas.push({ name: '版式', items: _allCateTypes.orientations, queryfield: 'orientation' })
        _cdatas.push({ name: '上线年份', items: _allCateTypes.eras, queryfield: 'era' })
        if (this.filtercates) {
            _cdatas = Object.assign(_cdatas, this.filtercates);
        }
        this.cateObj = _cdatas;

        res = await api.getInspirationStatis();
        this.inspirationInfo = res.data;
        window.addEventListener('scroll', this.docScroll)

        var defaultcolorhere = "#111111";
        var copalette = [["#111111", "#FFFFFF", "#9E9E9E", "#A48057", "#FC85B3", "#FF2727", "#FFA34B", "#FFD534", "#47C595", "#51C4C4", "#2B76E7", "#6D50ED"]];
        $("#colorfilter").spectrum({
            showPalette: true,
            maxSelectionSize: 0,
            showSelectionPalette: false,
            palette: copalette,
            showInput: true,
            preferredFormat: "hex6",
            clickoutFiresChange: false,
            cancelText: '清空',
            chooseText: "确定"
        })
            .on('change.spectrum', function (e, color) {
                that.queryParams.imageColor = $('.default-view-color span').attr('title');
                that.handleSearch();
            }).on('clear.spectrum', function (e, color) {
                that.queryParams.imageColor = '';
                that.handleSearch();
            })
    }
}

</script>

<style lang="less">
@import url('../../assets/style/spectrum.css');

.img-list-page {
    min-height:calc(100vh - 84px - 84px - 44px - 64px);
    .sch-sticky{
        top:244px;
    }
    .gp-filter {
        position: sticky;
        top: 169px !important;
        // z-index:1;
        // margin-top:20px;
        // padding-top:10px;
        // margin-bottom:21px;
        padding-bottom: 21px;
        padding-top: 10px !important;
        margin-bottom: 0px;
        margin-top: 0px;
        display: inline-block !important;
        width: 100%;

        .gp-img-layout {
            display: flex;
            align-items: center;

            .q-f-item-wrap {
                display: flex;
                align-items: center;
                // padding-left:10px;
                grid-gap: 5px;
            }
        }

        .mobile {
            display: none;
        }
    }

    .nav-cates {
        list-style: none;
        font-size: 16px;
        display: flex;
        align-items: center;
        padding-left: 30px;
        padding-right: 80px;

        li {
            line-height: 44px;
            border-radius: 44px;
            text-align: center;
            // min-width:100px;
            width: auto !important;
            background: #1D1D1F;
            display: block !important;
            margin-right: 20px;
            color: #6A6976;

            a {
                display: inline-block;
                width: 100%;
                padding: 0px 26px;
                white-space: nowrap;
            }

            &:hover {
                background: #323232;
                color: #fff;
            }
        }
    }

    .cate-page-prev {
        background: url('../../assets/pro/right_label_arrow.svg') no-repeat;
        width: 80px;
        height: 46px;
        transform: rotate(180deg);
        z-index: 1;
        left: 0px !important;

        &:after {
            display: none;
        }

        &:hover {
            background: url('../../assets/pro/right_label_arrow.svg') no-repeat;
            opacity: .6 !important;
        }
    }

    .cate-page-next {
        background: url('../../assets/pro/right_label_arrow.svg') no-repeat;
        width: 80px;
        height: 46px;
        z-index: 1;
        right: 0px;

        &:after {
            display: none;
        }

        &:hover {
            background: url('../../assets/pro/right_label_arrow.svg') no-repeat;
            opacity: .6 !important;
        }
    }

    .img-datas {
        margin-top: 0px;
        // padding-bottom: 100px;
        display: flex;
        align-items: flex-start;

        .img-list {
            width: 100%;
        }
        
        .cates{
            max-height:calc(100vh - 340px);
            min-height:calc(100vh - 340px);
        }
    }


    .gp-filter .seach-bx {
        overflow-x: auto;
    }
}
</style>